let dbConfig = require("../utils/dbconfig");
let fs = require("fs");
// 随机函数
function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

let validatePhoneCode = [];
let sendCodeP = (phone) => {
  for (let item of validatePhoneCode) {
    if (phone === item.phone) {
      return true;
    }
  }
  return false;
};

let findCodeAndPhone = (phone, code) => {
  for (let item of validatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return "login";
    }
    return "error";
  }
};

// 模拟发送验证码
sendCode = (req, res) => {
  let phone = req.query.phone;
  if (sendCodeP(phone)) {
    res.send({
      code: 500,
      message: "已发送验证码，请稍后重试",
    });
  }
  let code = rand(1000, 9999);
  validatePhoneCode.push({
    phone: phone,
    code: code,
  });
  res.send({
    code: "200",
    message: "发送成功",
    verificationCode: code,
  });
};

// 验证码登录
codePhoneLogin = async (req, res) => {
  let { phone, code } = req.query;
  // 验证手机号是否发送过验证码
  if (sendCodeP(phone)) {
    // 验证码和手机号是否匹配
    let status = findCodeAndPhone(phone, code);
    if (status == "login") {
      // 登录成功
      // 登录成功之后的操作
      let user = await phoneLoginBin(phone);

      res.send({
        code: 200,
        message: "登录成功",
        data: user[0],
      });
    } else if (status == "error") {
      res.send({
        code: 500,
        message: "登录失败",
      });
    }
  } else {
    res.send({
      code: 500,
      message: "未发送验证码",
    });
  }
};

// 检测验证码登录是否第一次登陆
let phoneLoginBin = async (phone) => {
  let sql = "select * from user where username=? or phone=?";
  let sqlArr = [phone, phone];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.lenght) {
    res[0].userinfo = await getUserInfo(res[0].id);
    return res;
  } else {
    // 用户第一次登陆注册用户并绑定表, 用户注册
    let res = await regUser(phone);
    // 获取用户详情
    res[0].userinfo = await getUserInfo(res[0].id);
    return res;
  }
};

// 用户注册方法
let regUser = async (phone) => {
  // 检测用户是否第一次注册
  let userpic =
    "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/05489ead0d0a573504e261a9d24bd352~300x300.image";
  let sql =
    "insert into user(username,userpic,phone,create_time) values(?,?,?,?)";
  let sqlArr = [phone, userpic, phone, new Date().valueOf()];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  // 执行成功后获取用户信息
  if (res.affectedRows === 1) {
    // 获取用户信息方法
    let user = await getUser(phone);
    // 创建用户副表
    let userinfo = await createUserInfo(user[0].id);
    if (userinfo.affectedRows == 1) {
      return user;
    } else {
      return false;
    }
  } else {
    return false;
  }
};

// 获取用户信息的方法
let getUser = (username) => {
  let sql = "select * from user where id=? or phone=? or username=?";
  let sqlArr = [username, username, username];
  return dbConfig.SySqlConnect(sql, sqlArr);
};

// 创建用户副表
let createUserInfo = (user_id) => {
  let sql = "insert into user_info(user_id, age, sex, job) values(?,?,?,?)";
  let sqlArr = [user_id, 18, 1, "未设置"];
  return dbConfig.SySqlConnect(sql, sqlArr);
};

// 获取注册用户详情
let getUserInfo = (user_id) => {
  let sql = "select age,sex,job,path,birthday from user_info where user_id=?";
  let sqlArr = [user_id];
  return dbConfig.SySqlConnect(sql, sqlArr);
};

// 查看用户详情
let findUserInfo = async (user_id) => {
  let sql = "select * from user_info where user_id=?";
  let sqlArr = [user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.lenght) {
    return true;
  }
  return false;
};

// 修改用户信息详情
let setUserInfo = async (user_id, age, sex, job, path, birthday) => {
  if (await findUserInfo(user_id)) {
    let sql =
      "update user_info set age=?,sex=?,job=?,path=?,birthday=? where user_id=?";
    let sqlArr = [age, sex, job, path, birthday, user_id];
    let res = await dbConfig.SySqlConnect(sql, sqlArr);
    if (res.affectedRows == 1) {
      // 成功
      let user = await getUser(user_id);
      let userinfo = await getUserInfo(user_id);
      user[0].userinfo = userinfo[0];
      return user;
    } else {
      return false;
    }
  } else {
    let sql =
      "insert into user_info (user_id,age,sex,job,path,birthday) values(?,?,?,?,?,?)";
    let sqlArr = [user_id, age, sex, job, path, birthday];
    let res = await dbConfig.SySqlConnect(sql, sqlArr);
    if (res.affectedRows == 1) {
      let user = await getUser(user_id);
      let userinfo = await getUserInfo(user_id);
      user[0].userinfo = userinfo[0];
      return user;
    } else {
      return false;
    }
  }
};

// 修改用户名称
let setUserName = async (user_id, username) => {
  let sql = "update user set username=? where id=?";
  let sqlArr = [username, user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.affectedRows == 1) {
    return true;
  } else {
    return false;
  }
};

// 检查用户密码
let checkUserPwd = async (user_id) => {
  // TODO: 判断id不能为空
  let sql = "select password from user where id=?";
  let sqlArr = [user_id];
  let res = await dbConfig.SySqlConnect(sql, sqlArr);
  if (res.length) {
    return res[0].password;
  } else {
    return 0;
  }
};

// 用户名、手机号登陆
login = (req, res) => {
  let username = req.query.username;
  let password = req.query.password;
  let phone = /^1[3|4|5|7|8][0-9]{9}$/;
  let email = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/;
  if (phone.test(username)) {
    // 账号登陆
    let sql =
      "select * from user where phone=? and password=? or username=? and password=?";
    let sqlArr = [username, password, username, password];
    let callBack = async (err, data) => {
      if (err) {
        res.send({
          code: 500,
          message: "出错了",
        });
      } else if (data === "") {
        res.send({
          code: 500,
          message: "用户名或密码错误",
          data: [],
        });
      } else {
        let user_id = data[0].id;
        let result = await getUserInfo(user_id);
        data[0].userinfo = result[0];
        res.send({
          code: 200,
          message: "登录成功",
          data: data[0],
        });
      }
    };
    dbConfig.sqlConnect(sql, sqlArr, callBack);
  } else if (email.test(username)) {
    // 邮箱登陆
    let sql = "select * from user where email=? and password=?";
    let sqlArr = [username, password];
    let callBack = async (err, data) => {
      if (err) {
        res.send({
          code: 500,
          message: "出错了",
        });
      } else if (data == "") {
        res.send({
          code: 500,
          message: "邮箱或密码错误",
          data: [],
        });
      } else {
        let user_id = data[0].id;
        let result = await getUserInfo(user_id);
        data[0].userinfo = result[0];
        res.send({
          code: 200,
          message: "登录成功",
          data: data[0],
        });
      }
    };
    dbConfig.sqlConnect(sql, sqlArr, callBack);
  } else {
    let sql = "select *  from user where username=? and password=?";
    let sqlArr = [username, password];
    let callBack = async (err, data) => {
      if (err) {
        res.send({
          code: 500,
          message: "出错了",
        });
      } else if (data == "") {
        res.send({
          code: 500,
          message: "邮箱、手机号或密码错误",
          data: [],
        });
      } else {
        let user_id = data[0].id;
        let result = await getUserInfo(user_id);
        data[0].userinfo = result[0];
        res.send({
          code: 200,
          message: "登录成功",
          data: data[0],
        });
      }
    };
    dbConfig.sqlConnect(sql, sqlArr, callBack);
  }
};

// 修改资料
editUserInfo = async (req, res) => {
  let { user_id, username, age, sex, job, path, birthday } = req.query;
  let result = await setUserName(user_id, username);
  if (result) {
    let resa = await setUserInfo(user_id, age, sex, job, path, birthday);
    if (resa.length) {
      res.send({
        code: 200,
        message: "修改成功",
        data: resa[0],
      });
    } else {
      res.send({
        code: 500,
        message: "修改失败",
      });
    }
  } else {
    res.send({
      code: 500,
      message: "修改失败1",
    });
  }
};

// 修改用户密码
setPassword = async (req, res) => {
  let { user_id, oldpassworld, newpassword } = req.query;
  // TODO：密码未加密
  // 检查用户的密码
  let userPwd = await checkUserPwd(user_id);
  if (userPwd) {
    if (userPwd == oldpassworld) {
      let sql = "update user set password=? where id=?";
      let sqlArr = [newpassword, user_id];
      let result = await dbConfig.SySqlConnect(sql, sqlArr);
      if (result.affectedRows == 1) {
        res.send({
          code: 200,
          message: "修改密码成功",
        });
      } else {
        res.send({
          code: 500,
          message: "修改密码失败",
        });
      }
    } else {
      res.send({
        code: 500,
        message: "密码不一致",
      });
    }
  } else {
    let sql = "update user set password=? where id=?";
    let sqlArr = [newpassword, user_id];
    let result = await dbConfig.SySqlConnect(sql, sqlArr);
    if (result.affectedRows == 1) {
      res.send({
        code: 200,
        message: "修改密码成功",
      });
    } else {
      res.send({
        code: 500,
        message: "修改密码失败",
      });
    }
  }
};

// 绑定邮箱
bindEmail = async (req, res) => {
  let { user_id, email } = req.query;
  let sql = "update user set email=? where id=?";
  let sqlArr = [email, user_id];
  let result = await dbConfig.SySqlConnect(sql, sqlArr);
  if (result.affectedRows == 1) {
    res.send({
      code: 200,
      message: "邮箱绑定成功",
    });
  } else {
    res.send({
      code: 500,
      message: "邮箱绑定失败",
    });
  }
};

// 修改用户默认头像
editUserImage = (req, res) => {
  if (req.file.length === 0) {
    res.render("error", { message: "上传文件不能为空！" });
  } else {
    let file = req.file;
    // 读取文件 随机名称 源文件名称
    fs.renameSync(
      "./public/uploads/" + file.filename,
      "./public/uploads/" + file.originalname
    );
    // 设置图片编码
    res.set({
      "content-type": "application/json; charset=utf8",
    });
    let { user_id } = req.query;
    let imgUrl = "http://localhost:3022/uploads/" + file.originalname;
    let sql = "update user set userpic=? where id=?";
    let sqlArr = [imgUrl, user_id];
    // 执行sql 传递 用户id和图片路径
    dbConfig.sqlConnect(sql, sqlArr, (err, data) => {
      if (err) {
        throw "上传异常";
      } else {
        if (data.affectedRows == 1) {
          res.send({
            code: 200,
            message: "修改成功",
            url: imgUrl,
          });
        } else {
          res.send({
            code: 500,
            message: "修改失败",
          });
        }
      }
    });
  }
};

// 批量上传
uploadMoreImg = (req, res) => {
  if (req.files.length === 0) {
    res.render("error", { message: "上传文件不能为空！" });
  } else {
    let sql = "insert into images (url,create_time,user_id) values ";
    let sqlArr = [];
    for (var i in req.files) {
      res.set({
        "content-type": "application/json; charset=utf8",
      });
      let file = req.files[i];
      fs.renameSync(
        "./public/uploads/" + file.filename,
        "./public/uploads/" + file.originalname
      );
      let { user_id } = req.query;
      let url = "http://localhost:3022/uploads/" + file.originalname;
      if (req.files.length - 1 == i) {
        sql += "(?)";
      } else {
        sql += "(?),";
      }
      // console.log(sql, "sql");
      sqlArr.push([url, new Date().valueOf(), user_id]);
      dbConfig.sqlConnect(sql, sqlArr, function (error, data) {
        if (error) {
          console.log("上传失败");
        } else {
          if (data.affectedRows > 0) {
            res.send({
              code: 200,
              message: "上传成功",
              affectedRows: data.affectedRows,
            });
          } else {
            res.send({
              code: 500,
              message: "上传失败",
            });
          }
        }
      });
    }
  }
};

// 视频发布
publlish = async (req, res) => {
  let { user_id, title, url, path, isopen, posting } = req.query;
  let sql =
    "insert into video (user_id, title, url, path, isopen, posting, create_time) values(?,?,?,?,?,?,?)";
  let sqlArr = [
    user_id,
    title,
    url,
    path,
    isopen,
    posting,
    new Date().valueOf(),
  ];
  let video_id = await dbConfig
    .SySqlConnect(sql, sqlArr)
    .then((res) => {
      return res.insertId;
    })
    .catch((err) => {
      return false;
    });
  if (video_id) {
    res.send({
      code: 200,
      msg: "发布成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "发布失败",
    });
  }
};

//退出
logout = (req, res) => {
  // TODO：没有Token
  res.send({
    code: 200,
    msg: "退出登录",
  });
};

module.exports = {
  sendCode,
  codePhoneLogin,
  login,
  editUserInfo,
  setPassword,
  bindEmail,
  editUserImage,
  uploadMoreImg,
  publlish,
  logout,
};
